package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.msg.SeckillGoodCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_ORDER_TAG

)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("进入创建订单的消费者中，执行秒杀操作");
        //从orderMessage拿出数据执行秒杀的操作
        Long seckillId = orderMessage.getSeckillId();
        Long userId = orderMessage.getUserId();
        String uuid = orderMessage.getUuid();
        Map<String, Object> data = new HashMap<>();
        data.put("seckillId",seckillId);
        data.put("userId",userId);
        data.put("uuid",uuid);
        try {
            //int i=1/0;
            //异步下单成功
            String orderNo = orderInfoService.doSeckill(userId, seckillId);
            data.put("data",orderNo);
            data.put("code",200);
            //发送异步下单成功的消息
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_SUCCESS_DEST,data);
        }catch (Exception e){
            //异步下单失败
            System.out.println("异步下单失败");
            e.printStackTrace();
            data.put("msg", SeckillGoodCodeMsg.CREATE_ORDER_FAIL.getMsg());
            data.put("code", SeckillGoodCodeMsg.CREATE_ORDER_FAIL.getCode());
            //发送异步下单失败的消息让websocket也能消费
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FAIL_DEST,data);

        }

    }
}
